package com.example.demo.threadExecutor;

import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @ClassName: ProducerConsumerDemo
 * @Description: 生产者消费者模型
 * @Author:
 * @Date
 */
public class ProducerConsumerDemo {

    static  class Producer{
        private ArrayBlockingQueue<String> queue;

        public Producer(ArrayBlockingQueue<String> queue) {
            this.queue = queue;
        }
        public boolean put(String date) {
            try {
                queue.put(date);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return true;
        }
    }

    static class Consumer {
        private  ArrayBlockingQueue<String> queue;

        public Consumer(ArrayBlockingQueue queue) {
            this.queue = queue;
        }

        public void get() {
           new Thread(new Runnable() {
               @Override
               public void run() {
                   while (true) {
                       try {
                           String date =  queue.take();
                           System.out.println("消费:" + date);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
               }
           }).start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue queue = new ArrayBlockingQueue<String>(20);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        consumer.get();
        while (true){
            System.out.println("投递元素");
            producer.put(UUID.randomUUID().toString());
            Thread.sleep(2000);
        }
    }
}
